package bmcsoft.webservicelearning;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class Exercise30_13Client extends JFrame {
    private JTextField jtfName = new JTextField();
    private JTextField jtfText = new JTextField();
    private JTextArea jta = new JTextArea();


    private DataOutputStream toExercise30_13Server;
    private DataInputStream fromExercise30_13Server;


    public static void main(String[] args) {
        new Exercise30_13Client();
    }

    public Exercise30_13Client(){
        //Panel p2 to hold the labels Name and Text
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(2,1));
        p1.add(new JLabel("Name"));
        p1.add(new JLabel("Enter Text"));

        //Panel p2 to hold jtfName,and jtfText
        JPanel p2 = new JPanel();
        p2.setLayout(new GridLayout(2,1));
        p2.add(jtfName);
        p2.add(jtfText);

        //Panel p1 and p2 into p
        JPanel p = new JPanel(new BorderLayout());
        p.add(p1,BorderLayout.WEST);
        p.add(p2,BorderLayout.CENTER);

        setLayout(new BorderLayout());
        add(p,BorderLayout.NORTH);
        add(new JScrollPane(jta),BorderLayout.CENTER);

        jtfName.addActionListener(new TextFieldListener());
        jtfText.addActionListener(new TextFieldListener());

        setTitle("Exercise30_13Client");
        setSize(300,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        try {
            Socket socket = new Socket("localhost",8080);

            fromExercise30_13Server = new DataInputStream(
                    socket.getInputStream()
            );
            toExercise30_13Server = new DataOutputStream(
                    socket.getOutputStream()
            );
        }catch (IOException ex){
            jta.append(ex.toString() + '\n');
        }
    }

    private class TextFieldListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            try {
                String  text = jtfName.getText().trim() + " : " + jtfText.getText().trim();
                toExercise30_13Server.writeUTF(text);
                toExercise30_13Server.flush();

                String area = fromExercise30_13Server.readUTF();

                jta.append(area + '\n');
            }catch (IOException ex){
                System.out.println(ex);
            }
        }
    }
}
